


rm(list=ls())
gc()

library(dplyr)
library(tidyr)
library(gt)
library(stringr)
library(tibble)
library(readr)
library(data.table)

s = fread('survey-population-comparison.csv.gz')


means = s[,list(
  Democrat = weighted.mean(Dem,w=w,na.rm=T),
  Married = weighted.mean(Married,w=w, na.rm=T),
  Republican = weighted.mean(Rep,w=w,na.rm=T),
  White = weighted.mean(White,w=w,na.rm=T),
  Black = weighted.mean(Black,w=w,na.rm=T),
  Hispanic=weighted.mean(Hispanic,w=w,na.rm=T),
  Asian = weighted.mean(Asian, w=w,na.rm=T),
  Female = weighted.mean(Female,w=w,na.rm=T),
  Age = weighted.mean(Age,w=w,na.rm=T),
  `Democratic Exposure` = weighted.mean(DemSpExp_nohh,w=w,na.rm=T),
  `Republican Exposure` = weighted.mean(RepSpExp_nohh,w=w,na.rm=T), 
 
  `Block Group White` = weighted.mean(WhiteBlockGroup,w=w,na.rm=T),
  `Block Group Registered` = weighted.mean(RegsBlockGroup,w=w,na.rm=T),
  `Block Group Median Age`=weighted.mean(AgeBlockGroup,w=w,na.rm=T),
  `Block Group Median Household Income` = weighted.mean(HHIncomeBlockGroup,w=w,na.rm=T),
  `Block Group Homeowner` = weighted.mean(HomeownerBlockGroup,w=w,na.rm=T),
  `Block Group Median Year House Built` = weighted.mean(YearBuiltBlockGroup,w=w,na.rm=T),
  `Block Group Drive to Work` = weighted.mean(DriveWorkBlockGroup,w=w,na.rm=T),
  `Block Group Median House Value` = weighted.mean(HouseValueBlockGroup,w=w,na.rm=T),
  `Vote 2016 General`= weighted.mean(GenVote2016,w=w,na.rm=T),
  
  `Vote 2018 General`= weighted.mean(GenVote2018,w=w,na.rm=T)
  
) ,by='Status']


t = as_tibble(means)%>%
  pivot_longer(Democrat:`Vote 2018 General`)%>%
  pivot_wider(names_from='Status')

out = t %>%
  gt %>%
  fmt_number(columns = 2:4, decimals = 3)%>%

  as_latex()%>%
  as.character()%>%
  str_replace_all('longtable','tabular')

write_file(out, 'tables/TabS14.tex')


